﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharepointSolutionInstaller.Views;
using SharepointSolutionInstaller.Resources;
using Microsoft.SharePoint.Administration;
using System.Data.SqlClient;
using SharepointSolutionInstaller.Utils.Configuration;

namespace SharepointSolutionInstaller.Utils.SolutionDeployment
{

    /// <summary>
    /// Command for creating an upgrade job.
    /// </summary>
    public class CreateUpgradeJobCommand : JobCommand
    {
        string solutionFile;
        Guid solutionId;
        internal CreateUpgradeJobCommand(InstallProcess parent,string solutionFile,Guid solutionId)
            : base(parent)
        {
            this.solutionFile = solutionFile;
            this.solutionId = solutionId;
        }

        internal override string Description
        {
            get
            {
                return CommonUIStrings.createUpgradeJobCommand;
            }
        }

        protected internal override bool Execute()
        {
            try
            {
                string filename = solutionFile;
                if (String.IsNullOrEmpty(filename))
                {
                    throw new Exception(CommonUIStrings.installExceptionConfigurationNoWsp);
                }

                SPSolution installedSolution = SPFarm.Local.Solutions[solutionId];

                //
                // Remove existing job, if any. 
                //
                if (installedSolution.JobExists)
                {
                    RemoveExistingJob(installedSolution);
                }

                log.Info(CommonUIStrings.logUpgrade);
                installedSolution.Upgrade(filename, GetImmediateJobTime());
                return true;
            }

            catch (SqlException ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
}
